package com.ErpCoreWeb.Common;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import com.ErpCoreModel.Base.CContext;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Store.CStore;


public class Global {

    static ServletContext m_application=null;
    

    private static CacheManager cacheManager = null;
  //缓存数据管理
    private static Lock _lockObjCache = new ReentrantLock();
    private static Cache _cache =null;
    //在线商店缓存
    private static Lock _lockObjCacheStore = new ReentrantLock();
    private static Cache _cacheStore =null;

    public Global()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    //创建数据库 sqlite 
    static public Boolean CreateDB(String sCompany)
    {
        ResourceBundle rb=ResourceBundle.getBundle("config");//WEB-INF/config.properties        
        String sPath = m_application.getRealPath(rb.getString("VirtualDir"));
        int idx = sPath.lastIndexOf('\\');
        sPath = sPath.substring(0, idx + 1);
        String sDestDir =sPath+ String.format("database\\sqlite\\%s\\", sCompany);
        File dir=new File(sDestDir);
        if (!dir.exists())
        {
        	dir.mkdirs();
        }
        String sSrc = sPath + String.format("database\\sqlite\\ErpCore_template.db");
        String sDest = sDestDir + String.format("ErpCore.db");
        
    	File fsrc=new File(sSrc);
    	File fdest=new File(sDest);
    	Util.fileChannelCopy(fsrc, fdest);
        
        return true;
    }
    static public CContext GetCtx(String sCompany,ServletContext application)
    {
        return GetCtx(application);//单个单位应用


//        CContext ctx = null;
//        if (!m_sortContext.containsKey(sCompany))
//        {
//            ctx = new CContext();
//            ResourceBundle rb=ResourceBundle.getBundle("config");//WEB-INF/config.properties        
//            String connstr = m_application.getRealPath(rb.getString("ConnectionString"));
//            String sPath = m_application.getRealPath(rb.getString("VirtualDir"));
//            int idx = sPath.lastIndexOf('\\');
//            sPath=sPath.substring(0,idx+1);
//            sPath += String.format("database\\sqlite\\%s\\ErpCore.db", sCompany);
//            File file = new File(sPath);
//            if (!file.exists())
//                return null;
//            connstr=String.format(connstr,sPath);
//
//            ctx.ConnectionString = connstr;
//            m_sortContext.put(sCompany, ctx);
//        }
//        else
//            ctx = m_sortContext.get(sCompany);
//        return ctx;
    }
    static public CContext GetCtx(ServletContext application)
    {
    	m_application=application;
    	//构造缓存
    	try {
			cacheManager = CacheManager.create(CContext.class.getClassLoader().getResourceAsStream("ehcache.xml"));
			_cache=cacheManager.getCache("ErpCoreModel");
			_cacheStore=cacheManager.getCache("Store");
		} catch (CacheException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	//

    	
        String sCompany = "ErpCore";

        CContext ctx = null;
        if (!_cache.isKeyInCache(sCompany))
        {
            ctx = new CContext();

            ResourceBundle rb=ResourceBundle.getBundle("config", Locale.getDefault());//WEB-INF/config.properties 
            ctx.DriverName = rb.getString("DriverName");
            ctx.ConnectionString = rb.getString("ConnectionString");
            ctx.UserName = rb.getString("UserName");
            ctx.PassWord = rb.getString("PassWord");
            
            Element element = new Element(sCompany, ctx);
            _cache.put(element);

        }
        else
            ctx = (CContext)_cache.get(sCompany).getValue();

        return ctx;
    }
    

    //设置文件上传路径
    static public void SetUploadPath(ServletContext application)
    {
        CContext ctx = GetCtx(application); 
        ResourceBundle rb=ResourceBundle.getBundle("config");//WEB-INF/config.properties        
        String sPath = application.getRealPath(rb.getString("VirtualDir"));
        //设置默认文件上传路径
        ctx.UploadPath = sPath + "\\UploadPath\\";
        File dir = new File(ctx.UploadPath);
        if (!dir.exists())
        	dir.mkdirs();

        //设置产品图片上传路径
        String sUploadPath = sPath + "\\Store\\ProductImg\\";
        dir = new File(sUploadPath);
        if (!dir.exists())
        	dir.mkdirs();

        CTable table = ctx.getTableMgr().FindByCode("SP_ProductImg");
        if (table != null)
        {
            CColumn col = (CColumn)table.getColumnMgr().FindByCode("Url");
            if (col != null)
                col.setUploadPath( sUploadPath);
        }
    }


    //获取桌面图标路径名称,用于拼接路径
    static public String GetDesktopIconPathName()
    {
        //在非SAAS系统中统一使用固定目录 ErpCore
        //if (HttpContext.Current.Session["TopCompany"] != null)
        //    return HttpContext.Current.Session["TopCompany"].ToString();
        return "ErpCore";
    }

  //判断传递参数为空
    public static boolean IsNullParameter(String val)
    {
    	if(val==null)
    		return true;
    	if(val.length()==0)
    		return true;
    	if(val.equalsIgnoreCase("null")) //解决空参数变成“null”
    		return true;
    	
    	return false;
    		
    }
    

    //在线商店
    static public CStore GetStore(String sCompany)
    {

        if (_cacheStore.isKeyInCache(sCompany))
        {
        	Element element =_cacheStore.get(sCompany);
        	return (CStore)element.getValue();
        }
        else
        {
            CStore store = new CStore();
            store.Ctx = GetCtx(sCompany,m_application);

            Element element = new Element(sCompany, store);
            _cacheStore.put(element);
            return store;
        }
    }
    static public CStore GetStore()
    {
        String sCompany = "ErpCore";
      //在非SAAS系统中统一使用固定目录 ErpCore
        //if (HttpContext.Current.Session["TopCompany"] != null)
        //    sCompany = HttpContext.Current.Session["TopCompany"].ToString();
        return GetStore(sCompany);
    }
}
